<template>
	<view class="pages">
		<u-navbar leftIconSize='30rpx' titleStyle="font-size: 26rpx;font-weight: 600;" title="编辑资料"
			@leftClick="$utils.back()" :placeholder="true" />
		<view style="flex: 1;overflow: hidden;">
			<scroll-view :scroll-y='true' style="height: 100%;">
				<view class="img">
					<button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar"></button>
					<u-avatar :src="avatar" size="180rpx"></u-avatar>
				</view>
				<u--form labelPosition="left" :model="data" ref="uForm" :labelStyle="{fontSize: '26rpx',}"
					labelWidth="200rpx">
					<u-form-item label="昵称" prop="name" borderBottom>
						<input type="nickname" v-model="data.name" style="text-align: right;" @blur='nameBlur' @change='changeName'/>
					</u-form-item>
					<u-form-item label="简介" prop="desc" borderBottom><u--input v-model="data.desc" border="none"
							inputAlign='right' /></u-form-item>
					<u-form-item label="性别" prop="sex" borderBottom @click="showSex = true; "><u--input
							v-model="data.sex" disabled inputAlign='right' disabledColor="#ffffff" placeholder="请选择性别"
							border="none" /></u-form-item>
					<u-form-item label="生日" prop="birthday" borderBottom @click="showBirthday = true; "><u--input
							v-model="data.birthday" disabled inputAlign='right' disabledColor="#ffffff"
							placeholder="请选择生日" border="none" /></u-form-item>
					<u-form-item label="职业标签" prop="label" borderBottom @click="showLabel=true">
						<view class="label">
							<text v-if="typeof_fun(data.label)&&data.label">{{data.label}}</text>
							<text v-else v-for="(item,index) in data.label" :key='index'>{{item}}</text>
						</view>
					</u-form-item>
					<u-form-item label="背景图" prop="src" borderBottom>
						<view style="display: flex;justify-content: flex-end;">
							<u-icon name="photo" label='上传个人主页背景图' size='26rpx' labelSize="26rpx" labelColor='#101010'
								@click="chooseImg()"></u-icon>
						</view>
					</u-form-item>
					<u-form-item label="是否公开" prop="open" borderBottom>
						<view style="display: flex;justify-content: flex-end;">
							<u-switch v-model="data.open" @change="change"></u-switch>
						</view>
					</u-form-item>
				</u--form>
			</scroll-view>
		</view>
		<view>
			<u-button type="primary" text="确定" @click="sumbit" shape='circle' :disabled='disabled'></u-button>
		</view>
		<root-portal>
			<u-action-sheet :show="showSex" :actions="actions" title="请选择性别" @close="showSex = false"
				@select="sexSelect">
			</u-action-sheet>
			<u-popup :show="showLabel" @close="showLabel=false">
				<view style="padding: 20rpx 40rpx;height: 30vh;">
					<view class="popupTitle" style="margin-bottom: 20rpx;">
						<u-icon name="close" size='26rpx' @click="showLabel=false"></u-icon>
						<text>编辑标签</text>
						<text @click="showLabel=false">确定</text>
					</view>
					<view class="label" style="justify-content: flex-start;">
						<text @click="addLable=data.label;addShow2=true;addIndex=0;" style="color: #101010;"
							v-if="typeof_fun(data.label)&&data.label">{{data.label}}</text>
						<text v-else @click="addLable=item;addShow2=true;addIndex=index;" style="color: #101010;"
							v-for="(item,index) in data.label" :key='index'>{{item}}</text>
						<text style="color: #101010;" @click="addShow_fun()">添加+</text>
					</view>
				</view>
			</u-popup>
			<u-modal :show="addShow2" cancelText='删除' confirmText='修改' @close='addShow2=false' showCancelButton='true'
				closeOnClickOverlay='true' @cancel='delLable' @confirm='add2'>
				<u--input v-model="addLable" border="surround" placeholder="请输入标签名" />
			</u-modal>
			<u-modal :show="addShow" confirmText='添加' @close='addShow=false' closeOnClickOverlay='true' @confirm='add'>
				<u--input v-model="addLable" border="surround" placeholder="请输入标签名" />
			</u-modal>
			<u-datetime-picker :minDate="100" ref="datetimePicker" closeOnClickOverlay='true' @close='close'
				@cancel='showBirthday=false;' @confirm='confirm' :show="showBirthday" v-model="date" mode="date"
				:formatter="formatter"></u-datetime-picker>
		</root-portal>

	</view>

</template>

<script>
	export default {
		computed: {
			userInfo() {
				return uni.getStorageSync('user')
			},
			profile() {
				return uni.getStorageSync('user')?.profile ? uni.getStorageSync('user')?.profile : {}
			},
		},
		data() {
			return {
				disabled:false,
				addShow2: false,
				date: Number(new Date()),
				showBirthday: false,
				avatar: '',
				addIndex: null,
				addLable: '',
				addShow: false,
				showLabel: false,
				actions: [{
						name: '男',
					},
					{
						name: '女',
					},
					{
						name: '保密',
					},
				],
				showSex: false,
				data: {
					name: '',
					desc: '',
					sex: '',
					label: [],
					src: '',
					open: true,
					birthday: ''
				}
			};
		},
		mounted() {
			this.data.desc = this.userInfo.brief_introduce
			this.avatar = this.userInfo.avatar
			this.data.name = this.userInfo.nick_name
			this.data.sex = this.profile.gender
			this.data.src = this.profile.bg_image
			this.data.birthday = this.profile.birthday
			if (typeof this.profile?.profession_tag == 'string') {
				this.data.label = this.profile?.profession_tag
			} else {
				this.data.label = this.profile.profession_tag ? [...this.profile.profession_tag] : []
			}

		},
		onReady() {
			// 微信小程序需要用此写法
			this.$refs.datetimePicker.setFormatter(this.formatter)
		},
		methods: {
			typeof_fun(str) {
				return typeof str == 'string'
			},
			addShow_fun() {
				if (this.data.label.length >= 3 && typeof this.data.label != 'string') {
					uni.$u.toast('标签不能超过三个')
					return
				}
				this.addShow = true;

			},
			changeName(e) {
				this.data.name = e.detail.value
			},
			nameBlur(e) {
				console.log(e)
				uni.setStorageSync('user', {
					...this.userInfo,
					nick_name: this.data.name
				});
				setTimeout(() => {
					this.$api.Edit.Nickname({
						nick_name: this.data.name
					})
				}, 2000)


			},
			confirm() {
				this.data.birthday = this.$u.timeFormat(this.date)
				this.close()
			},
			formatter(type, value) {
				if (type === 'year') {
					return `${value}年`
				}
				if (type === 'month') {
					return `${value}月`
				}
				if (type === 'day') {
					return `${value}日`
				}
				return value
			},
			close() {
				this.showBirthday = false;
			},
			onChooseAvatar(e) {
				const {
					avatarUrl
				} = e.detail;
				console.log(avatarUrl)
				uni.uploadFile({
					url: this.$config.url + '/api/my/detail/avatar/upload', // 仅为示例，非真实的接口地址
					filePath: avatarUrl,
					name: 'file',
					header: {
						'Content-Type': 'application/json;charset=UTF-8',
						'Authorization': "Bearer " + uni.getStorageSync('token')
					},
					success: (res) => {
						uni.setStorageSync('user', {
							...this.userInfo,
							avatar: avatarUrl,
						});
					}
				});
				this.avatar = avatarUrl;
			},
			sexSelect(e) {
				this.data.sex = e.name
			},
			change(e) {
				this.data.open = e
			},
			delLable() {
				if (typeof this.data.label != 'string') {
					this.data.label = this.data.label.filter(item => item != this.addLable)
				} else {
					this.data.label = ''
				}
				this.addShow2 = false
				this.addLable = null
				this.addIndex = null
			},

			add() {
				if (!this.addLable) {
					uni.$u.toast('请输入标签')
					return
				}
				this.data.label = [...this.data.label, this.addLable]
				this.addShow = false
				this.addLable = ''
				this.addIndex = null
			},
			add2() {
				if (!this.addLable) {
					uni.$u.toast('请输入标签')
					return
				}
				if (this.addIndex != null) {
					if (typeof this.data.label != 'string') {
						this.data.label.splice(this.addIndex, this.addIndex + 1)
					}
				}
				if (typeof this.data.label != 'string') {
					this.data.label.push(this.addLable)
				} else {
					this.data.label = this.addLable
				}
				this.addShow2 = false
				this.addLable = ''
				this.addIndex = null
			},
			sumbit() {
				this.disabled=true
				this.$api.Edit.Update({
					profession_tag: this.data.label,
					is_public: this.data.open ? 1 : 0,
					bg_image: this.data.src,
					birthday: this.data.birthday,
					gender: this.data.sex
				}).then(res => {
					this.$u.toast('修改成功')
					uni.setStorageSync('user', {
						...this.userInfo,
						avatar: this.avatar,
						nick_name: this.data.name,
						brief_introduce: this.data.desc,
						profile: {
							...this.profile,
							profession_tag: this.data.label,
							profession_tag: this.data.label,
							is_public: this.data.open ? 1 : 0,
							bg_image: this.data.src,
							birthday: this.data.birthday,
							gender: this.data.sex
						}
					});
					setTimeout(() => {
						this.$utils.back()
					}, 500)
				}).catch(err=>{
					uni.$u.toast(err.data.message)
					this.disabled=false
				})

			},
			chooseImg() {
				if(this.disabled)return
				uni.chooseImage({
					count: 1, // 默认9
					sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
					success: (res) => {
						this.disabled=true
						// 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
						uni.uploadFile({
							url: this.$config.url + '/api/image/upload', //仅为示例，非真实的接口地址
							filePath: res.tempFilePaths[0],
							name: 'file',
							header: {
								'Content-Type': 'application/json;charset=UTF-8',
								'Authorization': "Bearer " + uni.getStorageSync('token')
							},
							success: (res2) => {
								uni.$u.toast('图片上传成功')
								this.data.src = JSON.parse(res2.data).data.data.urlMedium
								this.disabled=false
							},
							fail(err) {
								console.log(err)
								this.disabled=false
							}
						});
					}
				})
			}

		}
	};
</script>

<style lang="scss" scoped>
	.popupTitle {
		display: flex;
		justify-content: space-between;
		font-size: 26rpx;
		color: #101010;

	}

	.label {
		font-size: 26rpx;
		display: flex;
		justify-content: flex-end;

		>text {
			margin-left: 20rpx;
			padding: 5rpx 10rpx;
			color: #fff;
			background-color: rgba($color: #020000, $alpha: 0.3);
			border-radius: 50rpx;
		}
	}

	.avatar-wrapper {
		opacity: 0;
		position: absolute;
		z-index: 5;
		width: 180rpx;
		height: 180rpx;
	}

	.img {
		top: 40rpx;
		width: 180rpx;
		position: relative;
		left: calc(50vw - 130rpx);
		margin-bottom: 80rpx;
	}

	.pages {
		box-sizing: border-box;
		display: flex;
		flex-direction: column;
		height: 100vh;
		padding: 0 40rpx;
		padding-bottom: constant(safe-area-inset-bottom) !important;
		/* 兼容 iOS 设备 */
		padding-bottom: env(safe-area-inset-bottom) !important;
	}
</style>